package com.kelaite.procurement.service.impl;

import io.jsonwebtoken.lang.Collections;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kelaite.procurement.dto.PurchaseOrderDTO;
import com.kelaite.procurement.dto.PurchaseOrderItemsDTO;
import com.kelaite.procurement.entity.TMaterialMasterClient;
import com.kelaite.procurement.entity.TPurchaseOrder;
import com.kelaite.procurement.entity.TPurchaseOrderItems;
import com.kelaite.procurement.entity.TSalesOrder;
import com.kelaite.procurement.entity.TSalesOrderItems;
import com.kelaite.procurement.entity.TUnit;
import com.kelaite.procurement.exception.BusinessException;
import com.kelaite.procurement.exception.DuplicateObjectException;
import com.kelaite.procurement.exception.NullObjectException;
import com.kelaite.procurement.exception.SubmitZeroItemsException;
import com.kelaite.procurement.repository.MaterialMasterClientRepository;
import com.kelaite.procurement.repository.PurchaseOrderItemsRepository;
import com.kelaite.procurement.repository.PurchaseOrderRepository;
import com.kelaite.procurement.repository.SalesOrderItemsRepository;
import com.kelaite.procurement.repository.SalesOrderRepository;
import com.kelaite.procurement.repository.UnitRepository;
import com.kelaite.procurement.service.PurchaseOrderItemsService;
import com.kelaite.procurement.utils.ConvertUtil;
import com.kelaite.procurement.utils.CurrentUserUtils;
import com.kelaite.procurement.dto.SalesOrderItemsDTO;

@Service
@Transactional
public class PurchaseOrderItemsServiceImpl implements PurchaseOrderItemsService {

	private final static Logger logger = Logger
			.getLogger(PurchaseOrderItemsServiceImpl.class);

	@Autowired
	private PurchaseOrderItemsRepository purchaseOrderItemsRepository;

	@Autowired
	private SalesOrderItemsRepository salesOrderItemsRepository;

	@Autowired
	private MaterialMasterClientRepository materialMasterClientRepository;

	@Autowired
	private PurchaseOrderRepository purchaseOrderRepository;

	@Autowired
	private UnitRepository unitRepository;

	@Autowired
	private SalesOrderRepository salesOrderRepository;

	@PersistenceContext
	private EntityManager em;

	@Override
	public TPurchaseOrderItems save(TPurchaseOrderItems persistence) {

		return this.purchaseOrderItemsRepository.save(persistence);
	}

	@Override
	public TPurchaseOrderItems getObject(Long id) {

		return this.purchaseOrderItemsRepository.findOne(id);
	}

	@Override
	public List<TPurchaseOrderItems> getAll() {

		return this.purchaseOrderItemsRepository.findAll();
	}

	@Override
	public void deleteByObject(TPurchaseOrderItems persistence) {

		this.purchaseOrderItemsRepository.delete(persistence);
	}

	@Override
	public void deleteByPrimaryKey(Long id) {

		this.purchaseOrderItemsRepository.delete(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TPurchaseOrderItems> getByProperty(String property, Object value) {

		Session session = (org.hibernate.Session) em.getDelegate();
		Criteria criteria = session.createCriteria(TPurchaseOrderItems.class)
				.add(Restrictions.eq(property, value));
		return criteria.list();
	}

	@Override
	public List<TPurchaseOrderItems> getByPurchaseOrderDTO(
			PurchaseOrderDTO purchaseOrderDTO) {

		if (null == purchaseOrderDTO || null == purchaseOrderDTO.getId()) {
			throw new BusinessException("purchaseOrderDTO is null. ");
		}
		return purchaseOrderItemsRepository
				.findByTPurchaseOrderOrderByOrderItemNoAsc(ConvertUtil
						.convertObj(purchaseOrderDTO, TPurchaseOrder.class));
	}

	@Override
	public int addPurchaseOrderItems(
			List<PurchaseOrderItemsDTO> purchaseOrderItemsList) {

		try {
			if (Collections.isEmpty(purchaseOrderItemsList)) {
				String msg = "PurchaseOrderItemsList is empty. ";
				logger.error(msg);
				throw new SubmitZeroItemsException(msg);
			}
			//
			for (PurchaseOrderItemsDTO purchaseOrderItemsDTO : purchaseOrderItemsList) {
				addPurchaseOrderItem(purchaseOrderItemsDTO);
			}
			return purchaseOrderItemsList.size();
		} catch (Exception e) {
			logger.error("addPurchaseOrderItems occurs exception. ", e);
			if (e instanceof SubmitZeroItemsException
					|| e instanceof DuplicateObjectException) {
				throw e;
			} else {
				throw new BusinessException(e);
			}
		}
	}

	private void addPurchaseOrderItem(
			PurchaseOrderItemsDTO purchaseOrderItemsDTO) {

		if (null == purchaseOrderItemsDTO) {
			throw new NullObjectException("PurchaseOrderItemsDTO is null. ");
		}
		// check repeat OrderItemNo
		int cnt = purchaseOrderItemsRepository
				.countByPurchaseOrderIdAndOrderItemNo(
						purchaseOrderItemsDTO.getPurchaseOrderId(),
						purchaseOrderItemsDTO.getOrderItemNo());
		if (cnt > 0) {
			String msg = String
					.format("PurchaseOrderItems with PurchaseOrderId[%s] and OrderItemNo[%s] exsist. ",
							purchaseOrderItemsDTO.getPurchaseOrderId(),
							purchaseOrderItemsDTO.getOrderItemNo());
			logger.error(msg);
			throw new DuplicateObjectException(msg);
		}
		//
		Date now = new Date();
		//
		String cUser = CurrentUserUtils.getInstance().getUsername();
		// material
		Long materialId = purchaseOrderItemsDTO.getMaterialId();
		if (null == materialId || materialId <= 0) {
			String msg = String.format(
					"PurchaseOrderItemsDTO.materialId[%s] is illegal.",
					materialId);
			logger.error(msg);
			throw new BusinessException(msg);
		}
		TMaterialMasterClient tMaterial = materialMasterClientRepository
				.findOne(materialId);
		if (null == tMaterial) {
			String msg = String.format(
					"TMaterialMasterClient[%s] not exsist. ", materialId);
			logger.error(msg);
			throw new BusinessException(msg);
		}
		// purchaseOrder
		Long purchaseOrderId = purchaseOrderItemsDTO.getPurchaseOrderId();
		if (null == purchaseOrderId || purchaseOrderId <= 0) {
			String msg = String.format(
					"PurchaseOrderItemsDTO.purchaseOrderId[%s] is illegal.",
					purchaseOrderId);
			logger.error(msg);
			throw new BusinessException(msg);
		}
		TPurchaseOrder tPurchaseOrder = purchaseOrderRepository
				.findOne(purchaseOrderId);
		if (null == tPurchaseOrder) {
			String msg = String.format("TPurchaseOrder[%s] not exsist. ",
					purchaseOrderId);
			logger.error(msg);
			throw new BusinessException(msg);
		}
		// salesOrder
		String salesOrderNo = tPurchaseOrder.getSalesOrderNo();
		if (StringUtils.isBlank(salesOrderNo)) {
			String msg = "TPurchaseOrder's salesOrderNo is null. ";
			logger.error(msg);
			throw new BusinessException(msg);
		}
		TSalesOrder tSalesOrder = salesOrderRepository
				.findBySalesOrderNo(salesOrderNo);
		if (null == tSalesOrder) {
			String msg = String.format("TSalesOrder[%s] not exsist. ",
					salesOrderNo);
			logger.error(msg);
			throw new BusinessException(msg);
		}
		// unit
		Long unitId = purchaseOrderItemsDTO.getUnitId();
		if (null == unitId || unitId <= 0) {
			String msg = String.format(
					"PurchaseOrderItemsDTO.unitId[%s] is illegal.", unitId);
			logger.error(msg);
			throw new BusinessException(msg);
		}
		TUnit tUnit = unitRepository.findOne(unitId);
		if (null == tUnit) {
			String msg = String.format("TUnit[%s] not exsist. ", unitId);
			logger.error(msg);
			throw new BusinessException(msg);
		}
		//
		// save PurcahseOrderItem
		TPurchaseOrderItems dbPurchaseOrderItems = ConvertUtil.convertObj(
				purchaseOrderItemsDTO, TPurchaseOrderItems.class);
		dbPurchaseOrderItems.setCreatedBy(cUser);
		dbPurchaseOrderItems.setGmtCreateTime(now);
		dbPurchaseOrderItems.setUpdatedBy(cUser);
		dbPurchaseOrderItems.setGmtUpdateTime(now);
		dbPurchaseOrderItems.setMaterialPic(tMaterial.getMaterialPic());
		dbPurchaseOrderItems.settMaterialMasterClient(tMaterial);
		dbPurchaseOrderItems.settUnit(tUnit);
		dbPurchaseOrderItems.settPurchaseOrder(tPurchaseOrder);
		dbPurchaseOrderItems = purchaseOrderItemsRepository
				.save(dbPurchaseOrderItems);
		//
		// save SalesOrderItem
		TSalesOrderItems dbSalesOrderItems = ConvertUtil.convertObj(
				dbPurchaseOrderItems, TSalesOrderItems.class);
		dbSalesOrderItems.setId(null);
		dbSalesOrderItems.settSalesOrder(tSalesOrder);
		dbSalesOrderItems.settUnit(tUnit);
		dbSalesOrderItems.settMaterialMasterClient(tMaterial);
		dbSalesOrderItems = salesOrderItemsRepository.save(dbSalesOrderItems);
	}
	
		@Override
	public int updatePurchaseOrderItems(List<SalesOrderItemsDTO> salesOrderItemsList) {
		//
		int i = 0;
		if (Collections.isEmpty(salesOrderItemsList))
			return i;
		//Date now = new Date();
		String cUser = CurrentUserUtils.getInstance().getUsername();

		for (SalesOrderItemsDTO salesOrderItem : salesOrderItemsList) {
			purchaseOrderItemsRepository.updatePurchaseOrderItems(salesOrderItem.getId(), 
					salesOrderItem.getQuantityDelivered()+salesOrderItem.getOldquantityDelivered(), 
					new Date(),
					salesOrderItem.getActualTime(), 
					cUser);
			++i;
		}
		return i;
	}
}
